<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类别编码" prop="categorynumber">
        <el-input
          v-model="queryParams.categorynumber"
          placeholder="请输入类别编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别名称" prop="categoryname">
        <el-input
          v-model="queryParams.categoryname"
          placeholder="请输入类别名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料BOM编码" label-width="120px" prop="materialbomnumber">
        <el-input
          v-model="queryParams.materialbomnumber"
          placeholder="请输入物料BOM编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料BOM名称" label-width="120px" prop="materialbomname">
        <el-input
          v-model="queryParams.materialbomname"
          placeholder="请输入物料BOM名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bomcostestimation/basedocument:asscategory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bomcostestimation/basedocument:asscategory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bomcostestimation/basedocument:asscategory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bomcostestimation/basedocument:asscategory:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport2"
          v-hasPermi="['bomcostestimation/basedocument:asscategory:export']"
        >导出类别为空的数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-download" plain size="mini" @click="importTemplate">下载导入模板
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" @click="importExcelsettlementrateentry">导入数据
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border stripe  :data="asscategoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="类别编码" align="center" prop="categorynumber" />
      <el-table-column label="类别名称" align="center" prop="categoryname" />
      <el-table-column label="物料BOM编码" align="center" prop="materialbomnumber" />
      <el-table-column label="物料BOM名称" align="center" prop="materialbomname" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bomcostestimation/basedocument:asscategory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bomcostestimation/basedocument:asscategory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改BOM类别关联对话框 -->
    <el-dialog :title="title" v-drag :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="类别编码" prop="categorynumber">
          <el-input v-model="form.categorynumber" placeholder="请输入类别编码" readonly />
          <span class="el-input__suffix">
                <span class="el-input__suffix-inner">
                  <i class="el-input_icon icon el-icon-search"
                     onmousemove="this.style.color='#366EDD'"
                     onmouseout="this.style.color='#919191'"
                     style="font-size: 16px;
                            position: absolute;
                            cursor: pointer;
                            right: 6px;
                            top: 8px;
                            background-color: #ffffff;"
                     @click="openF7('category',false,null)"
                  />
                </span>
              </span>
        </el-form-item>
        <el-form-item label="类别名称" prop="categoryname">
          <el-input v-model="form.categoryname" placeholder="请输入类别名称" disabled />
        </el-form-item>
        <el-form-item label="物料BOM编码" prop="materialbomnumber">
          <el-input v-model="form.materialbomnumber" placeholder="请输入物料BOM编码" readonly />
          <span class="el-input__suffix">
                <span class="el-input__suffix-inner">
                  <i class="el-input_icon icon el-icon-search"
                     onmousemove="this.style.color='#366EDD'"
                     onmouseout="this.style.color='#919191'"
                     style="font-size: 16px;
                            position: absolute;
                            cursor: pointer;
                            right: 6px;
                            top: 8px;
                            background-color: #ffffff;"
                     @click="openF7('materialhalf',false,null)"
                  />
                </span>
              </span>
        </el-form-item>
        <el-form-item label="物料BOM名称" prop="materialbomname">
          <el-input v-model="form.materialbomname" placeholder="请输入物料BOM名称" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <base-data-view @emitToParent="getF7Data" :tobasedata.sync='basedatadialog'></base-data-view>
    <el-dialog :title="excels.excelEntry.title" :visible.sync="excels.excelEntry.show" width="400px">
      <template v-show="excels.excelEntry.show">
        <div>
          <div class="container">
            {{ excels.excelEntry.upload_file || "导入" }}
            <input
              type="file"
              accept=".xls,.xlsx"
              class="upload_file"
              :value="excels.excelEntry.data"
              @change="readExcelsettlementrateentry($event)"
            />
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listAsscategory, getAsscategory, delAsscategory, addAsscategory, updateAsscategory ,importData} from "@/api/bomcostestimation/basedocument/asscategory";
import baseDataView from "@/views/bomcostestimation/f7View/baseDataView";
import * as XLSX1 from "xlsx";

export default {
  name: "Asscategory",
  components: {"baseDataView": baseDataView,},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      numbers: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BOM类别关联表格数据
      asscategoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      excels: {
        excelEntry: {
          show: false,
          excelList:[],
          upload_file: "",
          data: ""
        },
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryid: null,
        categoryname: null,
        categorynumber: null,
        materialbomid: null,
        materialbomname: null,
        materialbomnumber: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      basedatadialog:{
        material:{
          //是否显示特殊物料数据对话框
          isMatrialOpen:false,
          //选中的特殊物料信息
          selectedItem:null,
          //弹出的特殊物料是否用于查询
          isMatrialQuery:false,
          //是否为分录
          isEntry: false,
          row:null
        },
        specialmaterial:{
          show: false,
          index:null,
          row:null,
          isEntry:false,
        },
        category:{
          show: false,
          index:null,
          row:null,
          isEntry:false,
        },
        materialhalf:{
          show: false,
          index:null,
          row:null,
          isEntry:false,
        },
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询BOM类别关联列表 */
    getList() {
      this.loading = true;
      listAsscategory(this.queryParams).then(response => {
        this.asscategoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryid: null,
        categoryname: null,
        categorynumber: null,
        materialbomid: null,
        materialbomname: null,
        materialbomnumber: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.numbers = selection.map(item => item.materialbomnumber)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加BOM类别关联关系";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAsscategory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BOM类别关联关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAsscategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAsscategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const numbers = row.materialbomnumber || this.numbers;
      this.$modal.confirm('是否确认删除物料BOM编号编号为"' + numbers + '"的数据项？').then(function() {
        return delAsscategory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bomcostestimation/basedocument/asscategory/export', {
        ...this.queryParams
      }, `asscategory_${new Date().getTime()}.xlsx`)
    },
    /** 导出类别为空的数据按钮操作 */
    handleExport2() {
      this.download('bomcostestimation/basedocument/asscategory/export2', {
        ...this.queryParams
      }, `asscategory_${new Date().getTime()}.xlsx`)
    },
    //下载分录模板
    importTemplate() {
      let queryParams={
          pageNum: 1,
          pageSize: 10,
          categorynumber: "导出模板",
      }
      this.download('bomcostestimation/basedocument/asscategory/export', {
        ...queryParams
      }, `BOM类别关联导入模板_${new Date().getTime()}.xlsx`)
    },
    // 点击进行导入
    importExcelsettlementrateentry() {
      this.excels.excelEntry.upload_file = "";
      this.excels.excelEntry.data = "";
      this.excels.excelEntry.show = true;
    },
    //解析导入的excel文件
    readExcelsettlementrateentry(e) {
      // 读取表格文件
      let that = this;
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确，请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.excels.excelEntry.upload_file = files[0].name;
      }

      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX1.read(data, {
            type: "binary"
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX1.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          // 从解析出来的数据中提取相应的数据
          that.excels.excelEntry.excelList = [];
          ws.forEach(item => {
            that.excels.excelEntry.excelList.push({
              categorynumber: item["类别编码"],
              categoryname: item["类别名称"],
              materialbomnumber: item["物料BOM编码"],
              materialbomname: item["物料BOM名称"],
            });
          });
          importData(that.excels.excelEntry.excelList).then(response => {
            this.open = false;
            this.getList();
            this.$modal.msgWarning("后台导入中");
          });
          // 结束解析动画
          this.excels.excelEntry.show = false;
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    /** f7点击事件 */
    openF7(show,isEntry,row) {
      this.basedatadialog.F7dataType = show;
      switch (show) {
        case 'wfzbase':
          this.basedatadialog.wfzbase.show = !this.basedatadialog.wfzbase.show;
          break;
        case 'materialhalf':
          if(isEntry){
            this.basedatadialog.materialhalf.row = row;
            this.basedatadialog.materialhalf.isEntry = true;
          }
          this.basedatadialog.materialhalf.show = !this.basedatadialog.materialhalf.show;
          break;
        case 'category':
          if(isEntry){
            this.basedatadialog.category.row = row;
            this.basedatadialog.category.isEntry = true;
          }
          this.basedatadialog.category.show = !this.basedatadialog.category.show;
          break;
        case 'specialmaterial':
          if(isEntry){
            this.basedatadialog.specialmaterial.row = row;
            this.basedatadialog.specialmaterial.isEntry = true;
          }
          this.basedatadialog.specialmaterial.show = !this.basedatadialog.specialmaterial.show;
          break;
      }
    },
    /** f7获取值 */
    getF7Data(data) {
      switch (this.basedatadialog.F7dataType) {
        case "wfzbase":
          if (data.wfzbase != null) {
            this.form.f7wfzbaseNumber = data.wfzbase.fnumber;
            this.form.cfwfzbaseid = data.wfzbase.fid;
            this.form.f7wfzbaseName = data.wfzbase.fname;
            this.form.f7wfzbaseShow = data.wfzbase.fname;
          }
          break;
        case "category":
          if (data.category != null) {
            this.form.categoryid = data.category.id;
            this.form.categoryname = data.category.name;
            this.form.categorynumber = data.category.number;
          }
          break;
        case "materialhalf":
          if (data.materialhalf != null) {
            if(this.basedatadialog.materialhalf.isEntry){
            }else{
              this.form.materialbomid = data.materialhalf.fid;
              this.form.materialbomname = data.materialhalf.cfmaterialname;
              this.form.materialbomnumber = data.materialhalf.cfmaterialnumber;
            }
          }
          break;
      }
    }
    ,
  }
};
</script>
